<template>
	<el-card shadow="hover" class="layout-padding-auto">
		<operAuthTag service-name="common-service" path="/admin/imexport/task" oper-code="/list">
			<el-card shadow="hover">
				<div class="bar_btn_div">
					<div class="title_div">
						<div>筛选</div>
					</div>
					<div>
						<el-button size="default" @click="handleResetSearch()">重置搜索</el-button>
						<el-button type="primary" size="default" @click="refresh()">查询搜索</el-button>
					</div>
				</div>

				<div class="search_div">
					<el-form :model="state.ruleForm" label-width="120px">
						<div style="display: flex; flex-wrap: wrap">
							<el-form-item label="导出人" v-if='"adminImexport" === props.pageType'>
								<el-input v-model="state.ruleForm.createByName" class="input-width" placeholder="导出人"></el-input>
							</el-form-item>
							<el-form-item label="任务ID">
								<el-input v-model="state.ruleForm.taskId" class="input-width" placeholder="任务ID"></el-input>
							</el-form-item>
							<el-form-item label="文件名">
								<el-input v-model="state.ruleForm.fileName" class="input-width" placeholder="文件名"></el-input>
							</el-form-item>
							<el-form-item label="任务名称">
								<el-input v-model="state.ruleForm.taskName" class="input-width" placeholder="任务名称"></el-input>
							</el-form-item>
							<el-form-item label="任务状态">
								<el-select v-model="state.ruleForm.taskStatus" clearable="true">
									<dicItemsSelectOptions dicCode="导入导出任务状态" data-type="Int" :withNullValue="true" />
								</el-select>
							</el-form-item>

							<el-form-item label="创建时间">
								<el-date-picker v-model="state.ruleForm.createDate" type="datetimerange" :picker-options="state.pickerOptions" range-separator="至"
									start-placeholder="开始日期" end-placeholder="结束日期" align="right">
								</el-date-picker>
							</el-form-item>
						</div>
					</el-form>
				</div>
			</el-card>
		</operAuthTag>
		<el-card style="margin-top: 20px;" shadow="hover" class="layout-padding-auto">
			<el-table size="default" :data="state.dataList" style="width: 100%" :header-cell-class-name="handleHeaderClass" @sort-change="onSortHandler">
				<el-table-column label="任务ID" prop="taskId" width="80"></el-table-column>
				<el-table-column align="center" label="任务名称" prop="taskName" width="150" sortable="custom"></el-table-column>
				<el-table-column align="center" prop="fileName" label="文件名">
					<template #default="scope">
						<a href="javascript:void(0);" @click="downloadFile(scope.row.fileId, scope.row.fileName)">{{ scope.row.fileName }}</a>
					</template>
				</el-table-column>
				<el-table-column align="center" prop="taskType" label="类型" width="80">
					<template #default="scope">
						<el-tag :type="scope.row.taskType === 1 ? 'success' : 'warning'" effect="dark">{{
							scope.row.taskType === 1 ? '导入' : '导出'
						}}</el-tag>
					</template>
				</el-table-column>
				<el-table-column align="center" prop="startTime" label="开始执行时间" width="180">
				</el-table-column>
				<el-table-column align="center" prop="endTime" label="结束执行时间" width="180">
				</el-table-column>
				<el-table-column align="center" prop="executeSeconds" label="执行时长" width="180" sortable="custom">
				</el-table-column>

				<!-- 1(未执行) 2(执行中)3(执行成功)-1(执行失败) -->
				<el-table-column align="center" prop="taskStatus" label="执行状态" width="140">
					<template #default="scope">
						<dicItemsETag dicCode="导入导出任务状态" :value="scope.row.taskStatus" :key="scope.row.taskStatus"
							:type="scope.row.taskStatus === 3 ? 'success' : scope.row.taskStatus === -1 ? 'error' : 'warning'" />
					</template>
				</el-table-column>
				<el-table-column align="center" prop="message" label="任务消息" />
				<el-table-column align="center" prop="createByName" label="创建人" width="100" v-if='"adminImexport" === props.pageType' />
				<el-table-column align="center" prop="createDate" label="创建时间" width="180" sortable="custom">
					<!-- <template #default="scope">
						<span>{{ formatDate( new Date(scope.row.createDate), "YYYY-mm-dd HH:MM:SS") }}</span>
					</template> -->
				</el-table-column>
			</el-table>
		</el-card>
		<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15" :pager-count="5" :page-sizes="[10, 20, 30]"
			v-model:current-page="state.page" background v-model:page-size="state.limit" layout="total, sizes, prev, pager, next, jumper" :total="state.total">
		</el-pagination>
	</el-card>
</template>

<script setup lang="ts" name="imexportPage">

import { onMounted, reactive, defineProps, defineAsyncComponent } from 'vue';
import { ElMessage } from 'element-plus';

import { imexportApi } from '/@/api/imexport/index';
import { camelToUnderline } from '/@/utils/StringFormat';

const dicItemsETag = defineAsyncComponent(() => import('/@/components/dic/dicItemsETag.vue'));
const dicItemsSelectOptions = defineAsyncComponent(() => import('/@/components/dic/dicItemsSelectOptions.vue'));
const operAuthTag = defineAsyncComponent(() => import('/@/components/operAuthTag.vue'));

// defineProps<{ type: String, typeName: String }>()

const props = defineProps({ pageType: String, pageName: String })

const state = reactive({
	page: 1,
	limit: 10,
	total: 0,
	sorts: { "createDate": "descending" },
	dataList: [] as any,
	ruleForm: {
		taskId: null,
		createByName: null,
		fileName: null,
		createDate: null,
		taskName: null,
		taskStatus: null,
	},
	taskStatus: {
		"1": "未执行",
		"2": "执行中",
		"3": "执行成功",
		"-1": "执行失败",
	},
	pickerOptions: {
		shortcuts: [
			{
				text: "最近一周",
				onClick(picker: any) {
					const end = new Date();
					const start = new Date();
					start.setTime(
						start.getTime() - 3600 * 1000 * 24 * 7
					);
					picker.$emit("pick", [start, end]);
				},
			},
			{
				text: "最近一个月",
				onClick(picker: any) {
					const end = new Date();
					const start = new Date();
					start.setTime(
						start.getTime() - 3600 * 1000 * 24 * 30
					);
					picker.$emit("pick", [start, end]);
				},
			},
			{
				text: "最近三个月",
				onClick(picker: any) {
					const end = new Date();
					const start = new Date();
					start.setTime(
						start.getTime() - 3600 * 1000 * 24 * 90
					);
					picker.$emit("pick", [start, end]);
				},
			},
		],
	},

});

const handleHeaderClass = (column: any) => {
	if (column.column.property) {
		column.column.order = state.sorts[column.column.property];
	}
};
const sortsStr = () => {
	var result = "";
	for (var prop in state.sorts) {
		result += camelToUnderline(prop) + (state.sorts[prop] == "descending" ? " desc," : " asc,")
	}
	if (result == "") {
		return null;
	}
	return result.substring(0, result.length - 1)
};
const onSortHandler = (column: any) => {
	if (column.order) {
		state.sorts[column.prop] = column.order
	} else if (state.sorts[column.prop]) {
		delete state.sorts[column.prop];
	}
	getTaskList();
};


const getTaskList = async () => {

	let vo = {
		page: state.page,
		limit: state.limit,
		sorts: sortsStr()
	} as any;

	let queryParams = {
		createDate: String
	};



	for (let prop in state.ruleForm) {
		if (prop == "createDate") {
			if (state.ruleForm.createDate) {
				queryParams.createDate = state.ruleForm.createDate[0].getTime() + "," + state.ruleForm.createDate[1].getTime();
			}
		} else {
			if (state.ruleForm[prop]) {
				queryParams[prop] = state.ruleForm[prop];
			}
		}
	}

	let tempList = {};

	if ("myImexport" === props.pageType) {
		tempList = await imexportApi().userQueryTask(Object.assign({}, vo, queryParams));
	} else if ("adminImexport" === props.pageType) {
		tempList = await imexportApi().adminQueryTask(Object.assign({}, vo, queryParams));
	}

	state.dataList = tempList.list;
	state.total = tempList.total;


}

// 分页改变
const onHandleSizeChange = (val: number) => {

	state.limit = val;
	getTaskList();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.page = val;
	getTaskList();
};


const handleResetSearch = () => {
	state.ruleForm = {
		taskId: null,
		createByName: null,
		fileName: null,
		createDate: null,
		taskName: null
	};
	state.page = 1;
	state.limit = 10;
	getTaskList();
}


const refresh = () => {
	getTaskList();
}



const downloadFile = async (_id: String, filename: string) => {
	try {
		await imexportApi().downloadFile("myImexport" === props.pageType ? "personal" : "admin", _id).then(response => {
			if (window.navigator.msSaveOrOpenBlob) {
				navigator.msSaveBlob(response, filename);
			} else {
				var link = document.createElement("a");
				link.href = window.URL.createObjectURL(response);
				link.download = filename;
				link.click();
				window.URL.revokeObjectURL(link.href);
			}
		});
	} catch (error) {
		ElMessage.error("文件下载失败，请检查!");
	}
	ElMessage.success({ message: '下载成功', type: 'success', });
}
// 页面加载时
onMounted(() => {
	getTaskList()
});



</script>
<style scoped lang="scss">
.el-form .el-form-item:last-of-type {
	margin-bottom: 22px !important;
}

.bar_tools {
	display: flex;
	flex-direction: row-reverse;
	margin-bottom: 10px;
}


.bar_btn_div {
	display: flex;
	padding: 20px;
	border: 1px solid #ebeef5;
	align-items: center;
	justify-content: space-between;
	border-radius: 5px 5px 0px 0px;
	padding: 10px;
	padding-left: 20px;
	padding-right: 20px;

	.title_div {
		display: flex;
		font-size: 16px;

		&>div {
			margin-right: 10px;
		}
	}
}

.search_div {
	border: 1px solid #ebeef5;
	border-top: 0px;
	border-radius: 0px 0px 5px 5px;
	padding: 20px;
	padding-bottom: 0px;
}
</style>